
import re
import os

# 要统计的目录
inputPath = input("请输入要操作的目录路径：")
if inputPath == '' :
	inputPath = 'D:\WorkSpace\gitee\my-python-tool\\test'

# 要替换的字符 (a:b; a替换成b) 
replaceSrtDict = {"jvs": "kmf"}
unReplaceContentFileTypeDict = {"ttf": True, "jpg": True, "png": True, "gif": True, "jpeg": True, "ico": True, "ico1": True, "svg": True, }
# 不需要替换文件内容的文件类型
unReplaceTypes = ["ttf", "jpg", "png", "gif", "jpeg", "ico", "ico1", "svg"]
# 要忽略的文件夹
unReplaceFolder = ["node_modules", ".git"]

# 替换文件内容
def replaceFileContent(path, oldStr, newStr):
	errorList = []
	paths = os.listdir(path)
	for nowPath in paths:
		absNowPath = os.path.join(path, nowPath)
		if os.path.isdir(absNowPath) and unReplaceFolder.count(nowPath) == 0:
			errorList += replaceFileContent(absNowPath, oldStr, newStr)
		else:
			if os.path.isfile(absNowPath):
				fileNameSp = nowPath.split(".")
				fileType = fileNameSp[len(fileNameSp) - 1]
				if unReplaceTypes.count(fileType) == 0:
					print("替换文件内容", absNowPath)
					try:
						with open(absNowPath, "r", 2048, "utf8") as file:
							fileContent = file.read()
							newFileContent = fileContent.replace(oldStr, newStr)
							with open(absNowPath, "w", 2048, "utf8") as file:
								file.write(newFileContent)
					except UnicodeDecodeError:
						print("\033[0;33mWarning: 文件 " + absNowPath + " 内容读取异常\033[0m")
						errorList.append(absNowPath)
	return errorList

# 替换文件/目录名
def replaceDirAndFileName(path, oldStr, newStr):
	paths = os.listdir(path)
	for nowPath in paths:
		absNowPath = os.path.join(path, nowPath)
		if os.path.isdir(absNowPath):
			replaceDirAndFileName(absNowPath, oldStr, newStr)
		newNowPath = nowPath.replace(oldStr, newStr)
		newAbsNowPath = os.path.join(path, newNowPath)
		if newNowPath != nowPath:
			print("替换文件/目录名: ", absNowPath)
			print("\033[0;32m              -->", newAbsNowPath, "\033[0m")
			os.rename(absNowPath, newAbsNowPath)
	return

# 替换
def replace(path):
	errorList = []
	for oldStr in replaceSrtDict:
		print("开始替换 ", oldStr, " 为 ", replaceSrtDict[oldStr], " ...")
		print("开始替换文件内容...")
		errorList = replaceFileContent(path, oldStr, replaceSrtDict[oldStr])
		print("替换文件内容完毕! \n")
		print("开始替换文件/目录名...")
		replaceDirAndFileName(path, oldStr, replaceSrtDict[oldStr])
		print("替换文件/目录内容完毕! ")
		print("替换 ", oldStr, " 为 ", replaceSrtDict[oldStr], " 完毕! \n")
	
	if len(errorList) > 0:
		print("\033[0;33mWarning: 以下文件读取内容失败: ")
		for readErrorFile in errorList:
			print(readErrorFile)
		print("\033[0m")
	return

print(inputPath)
replace(inputPath)